package com.itheima.search.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.vo.ResultVo;
import com.itheima.core.controller.AbstractCoreController;
import com.itheima.search.pojo.ApAssociateWords;
import com.itheima.search.dto.SearchDto;
import com.itheima.search.mapper.ApAssociateWordsMapper;
import com.itheima.search.pojo.ApAssociateWords;
import com.itheima.search.service.ApAssociateWordsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.trie4j.patricia.PatriciaTrie;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description <p>联想词 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.search.service.impl
 */
@Service
public class ApAssociateWordsServiceImpl extends ServiceImpl<ApAssociateWordsMapper, ApAssociateWords> implements ApAssociateWordsService {
    @Autowired
    private PatriciaTrie pat;

    /**
     * 搜索词联想
     *
     * @param dto
     * @return
     */
    @Override
    public List<String> search(SearchDto dto) {
        IPage<ApAssociateWords> pageInfo = new Page<ApAssociateWords>(1,10);
        LambdaQueryWrapper<ApAssociateWords> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(dto.getSearchWords()),ApAssociateWords::getAssociateWords,dto.getSearchWords());
        lqw.orderByDesc(ApAssociateWords::getCreatedTime);
        page(pageInfo,lqw);
        List<ApAssociateWords> records = pageInfo.getRecords();
        List<String> list = new ArrayList<>();
        if(!CollectionUtils.isEmpty(records)){
            list = records.stream().map(ApAssociateWords::getAssociateWords).collect(Collectors.toList());
        }
        return list;
    }

    /**
     * 使用字典树
     *
     * @param dto
     * @return
     */
    @Override
    public List<String> searchV2(SearchDto dto) {
        List<String> list = new ArrayList<>();
        if(null != dto && StringUtils.isNotEmpty(dto.getSearchWords())){
            pat.insert(dto.getSearchWords());
            // 前缀匹配
            list = (List<String>)pat.predictiveSearch(dto.getSearchWords());
            if(list.size() > 10){
                return list.subList(0,10);
            }
        }
        return list;

    }


}